var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../common/common');
var DBConfig = require('../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);

var fs = require('fs');
var co = require('co');
var OSS = require('ali-oss');
var client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI97ZN2efVb0kK',
  accessKeySecret: 'R8XT8y00l5M827strb1EhTms6TQPsP'
});

var ali_oss = {
	bucket: 'jkyximage',
	endPoint: 'http://oss-cn-beijing.aliyuncs.com',
}

var multer  = require('multer')
var upload = multer({ dest: 'tmp/' })
// 图片上传
router.post('/jkyx/pc_upload', upload.single('file'), function(req, res, next){
	var parma = req.body;
	var id = parma.id || '';
	// 文件路径
	var filePath = './' + req.file.path; 
	// 文件类型
	var temp = req.file.originalname.split('.');
	var fileType = temp[temp.length - 1];
	var lastName = '.' + fileType;
	// 构建图片名
	var fileName = Date.now() + lastName;
	
	fs.rename(filePath, fileName, (err) => {
		if (err) {
			res.end(JSON.stringify({status:'102',msg:'文件写入失败'}));	
		}else{
			var localFile = './' + fileName;  
			var key = fileName;
			// 阿里云 上传文件	
			co(function* () {
			  client.useBucket(ali_oss.bucket);
			  var result = yield client.put(key, localFile);
			  var imageSrc = 'http://jkyximage.oss-cn-beijing.aliyuncs.com/' + result.name;
			  // 上传之后删除本地文件
			  fs.unlinkSync(localFile);
			  pool.getConnection(function(err, connection) {
					if(err){
						res.end(JSON.stringify({
			     			msg: '数据库连接失败',
			     			status:'101',
			     		}));
					}
					connection.query(DBConfig.pc_upload_image,[id,imageSrc,CommonJS.getNowFormatDate()],function (err, results) {
						connection.release();
						if (err){
						  	throw err
						}else{
						  	res.end(JSON.stringify({
						  		status:'100',
						  		msg:'上传成功',
						  		imageUrl:imageSrc,
						  		index: id
						  	}));
						}
					})
				})
			}).catch(function (err) {
			  // 上传之后删除本地文件
			  fs.unlinkSync(localFile);
			  res.end(JSON.stringify({status:'101',msg:'上传失败',error:JSON.stringify(err)}));	
			});
		}
	})
})




module.exports = router;
